package com.changeover.gwt.client.controller;

import com.changeover.gwt.client.event.LogoutEvent;
import com.changeover.gwt.client.view.IMainView;
import com.changeover.gwt.shared.model.customer.ComplexCustomer;
import com.changeover.gwt.shared.model.customer.ICustomer;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.view.client.NoSelectionModel;
import com.google.gwt.view.client.SelectionChangeEvent;

public class MainController implements Controller {

    private final HandlerManager eventBus;
    private final IMainView view;

    public MainController(HandlerManager eventBus, IMainView view) {
        this.eventBus = eventBus;
        this.view = view;
    }

    private void bind() {
        final NoSelectionModel<ICustomer> complexSelectionModel = new NoSelectionModel<ICustomer>();
        view.getTaskView().getComplexCustomerGridView().getDataGrid().setSelectionModel(complexSelectionModel);
        complexSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            @Override
            public void onSelectionChange(SelectionChangeEvent event) {
                ComplexCustomer customer = new ComplexCustomer();
                customer = (ComplexCustomer)complexSelectionModel.getLastSelectedObject();
                view.setCustomer(customer);
//                eventBus.fireEvent(new CustomerDetailsEvent(customer));
            }
        });
        
        final NoSelectionModel<ICustomer> standartSelectionModel = new NoSelectionModel<ICustomer>();
        view.getTaskView().getStandardCustomerGridView().getDataGrid().setSelectionModel(standartSelectionModel);
        standartSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
            @Override
            public void onSelectionChange(SelectionChangeEvent event) {
                ComplexCustomer customer = new ComplexCustomer();
                customer = (ComplexCustomer)standartSelectionModel.getLastSelectedObject();
//                eventBus.fireEvent(new CustomerDetailsEvent(customer));
                view.setCustomer(customer);
            }
        });
        
        view.getLogoutLink().addClickHandler(new ClickHandler() {
            
            @Override
            public void onClick(ClickEvent event) {
                eventBus.fireEvent(new LogoutEvent());
            }
        });
    }

    @Override
    public void go(HasWidgets container) {
        bind();
        container.clear();
        container.add(view.asWidget());
    }

}
